package com.lyd.sweet.feign.config;

import com.lyd.sweet.feign.decoder.FeignSuccessDecoder;
import com.lyd.sweet.feign.decoder.FeignErrorDecoder;
import feign.RequestInterceptor;
import feign.codec.Decoder;
import feign.codec.ErrorDecoder;
import feign.optionals.OptionalDecoder;
import com.lyd.sweet.feign.interceptor.FeignInterceptor;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.support.ResponseEntityDecoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Feign的自动配置。
 * 约定FeignClient的定义统一放在“com.”目录下任一个目录，自动配置扫描该路径。
 * 默认情况下Feign重试机制为关闭，如需要开启重试策略，扩展此配置类增加设置。
 * 定义feign响应结果解码器
 * 通过spring.factories自动注册
 *
 * @author: 木木
 */
@Configuration
@EnableFeignClients(basePackages = {"com.**"})
public class FeignConfig {

    /**
     * feign的顶层过滤器
     *
     * @return
     */
    @Bean
    public RequestInterceptor requestInterceptor() {
        return new FeignInterceptor();
    }

    /**
     * feign响应结果适配器是否开启,默认开启
     *
     * @param messageConverters
     * @return
     */
    @Bean
    @ConditionalOnProperty(name = "sweet.feign.response.adapter.enabled", havingValue = "true", matchIfMissing = true)
    public Decoder feignDecoder(ObjectFactory<HttpMessageConverters> messageConverters) {
        return new OptionalDecoder((new ResponseEntityDecoder(new FeignSuccessDecoder(messageConverters))));
    }

    /**
     * feign异常消息解码器
     *
     * @return
     */
    @Bean
    public ErrorDecoder feignErrorDecoder() {
        return new FeignErrorDecoder();
    }
}
